﻿using Microsoft.Win32;
using PFC.Program.Verification;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace PFC.Program.Profile
{
    /// <summary>
    /// Логика взаимодействия для profile_Window.xaml
    /// </summary>
    public partial class profile_Window : Window
    {
        public profile_Window()
        {
            InitializeComponent();

            // Передача логина в окно
            loginUser_Txb.Text = GlobalVaribles.login;

            // Передача аватарки в окно
            SqlDataReader readerImage = ClassRequests.GetAva_Profile(GlobalVaribles.prof_ID);
            try
            {
                while (readerImage.Read())
                {
                    byte[] avaBytes = (byte[])readerImage["avatar"];
                    MemoryStream ms = new MemoryStream();
                    ms.Write(avaBytes, 0, avaBytes.Length);
                    BitmapImage bmp = new BitmapImage();
                    bmp.BeginInit();
                    bmp.StreamSource = ms;
                    try { bmp.EndInit(); }
                    catch { ava_Img.ImageSource = BitmapFrame.Create(new Uri(@"pack://application:,,,/Resources/user.png")); return; }
                    ava_Img.ImageSource = bmp;
                }
            } catch (System.InvalidCastException) { }

            readerImage.Close();
            CommonClass.GetConnection().Close();
        }

        /* Выход в окно верификации */
        private void exit_Btn_Click(object sender, RoutedEventArgs e)
        {
            verif_Window verWin = new verif_Window();
            verWin.Show();
            this.Close();
        }

        /* Смена картинки */
        private void ava_Img_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Multiselect = false,
                Filter = "Image files (*.png; *.jpeg)| *.png; *.jpeg"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                string filepath = openFileDialog.FileName;
                string filepathBacup = openFileDialog.FileName;
                try
                {
                    ClassRequests.UpdateAva_Profile(GlobalVaribles.prof_ID, filepath);

                    SqlDataReader readerImage = ClassRequests.GetAva_Profile(GlobalVaribles.prof_ID);
                    while (readerImage.Read())
                    {
                        byte[] avaBytes = (byte[])readerImage["avatar"];
                        MemoryStream ms = new MemoryStream();
                        ms.Write(avaBytes, 0, avaBytes.Length);
                        BitmapImage bmp = new BitmapImage();
                        bmp.BeginInit();
                        bmp.StreamSource = ms;
                        bmp.EndInit();
                        ava_Img.ImageSource = bmp;
                    }
                } catch (Exception ex) { 
                    MessageBox.Show("Ошибка: " + ex.Message + "\n" + "Возвращение картинки");

                    ClassRequests.UpdateAva_Profile(GlobalVaribles.prof_ID, filepathBacup);

                    SqlDataReader readerImage = ClassRequests.GetAva_Profile(GlobalVaribles.prof_ID);
                    while (readerImage.Read())
                    {
                        byte[] avaBytes = (byte[])readerImage["avatar"];
                        MemoryStream ms = new MemoryStream();
                        ms.Write(avaBytes, 0, avaBytes.Length);
                        BitmapImage bmp = new BitmapImage();
                        bmp.BeginInit();
                        bmp.StreamSource = ms;
                        try { bmp.EndInit(); 
                        } catch { ava_Img.ImageSource = BitmapFrame.Create(new Uri(@"pack://application:,,,/Resources/user.png")); return; }
                        ava_Img.ImageSource = bmp;
                    }
                }
            }
        }

        // Удаление профиля
        private void DeleteProfileBtn_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Вы уверены, что хотите УДАЛИТЬ профиль?", "Удаление профиля", MessageBoxButton.YesNo,
                                MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                ClassRequests.DeleteProfile();
                verif_Window verWin = new verif_Window();
                verWin.Show();
                this.Close();
                MessageBox.Show("Профиль удален!", "Удаление профиля", MessageBoxButton.OK,
                                MessageBoxImage.Information);
            }
        }
    }
}
